package com.gitee.wsl.struct.tree.ext

import com.gitee.wsl.struct.tree.NodeElement
import com.gitee.wsl.struct.tree.TreeElement

fun <T,E: TreeElement<T, E>> TreeElement<T, E>.prettyString(): String {
    val stringBuilder = StringBuilder()
    print(stringBuilder, "", "")
    return stringBuilder.toString()
}

private fun <T,E: TreeElement<T, E>> TreeElement<T, E>.print(stringBuilder: StringBuilder, prefix: String, childrenPrefix: String) {
    stringBuilder.append(prefix)
    stringBuilder.append(this.data)
    stringBuilder.append('\n')
    if(!isLeaf && this is NodeElement) {
        val childIterator = children!!.iterator()
        while (childIterator.hasNext()) {
            val node = childIterator.next()
            if (childIterator.hasNext()) {
                node.print(stringBuilder, "$childrenPrefix├── ", "$childrenPrefix│   ")
            } else {
                node.print(stringBuilder, "$childrenPrefix└── ", "$childrenPrefix    ")
            }
        }
    }
}